package com.xxx.zkconfig;

import com.alibaba.druid.pool.DruidDataSource;
import com.xxx.zkconfig.helper.FastJsonSerializer;
import com.xxx.zkconfig.helper.NodeChangeListenerUtils;
import com.xxx.zkconfig.helper.PropertyReader;
import com.xxx.zkconfig.helper.ZkUtils;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
import org.apache.curator.framework.recipes.cache.TreeCacheEvent;
import org.apache.curator.framework.recipes.cache.TreeCacheListener;
import org.springframework.beans.BeansException;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.support.AbstractApplicationContext;

import javax.sql.DataSource;
import java.util.Map;
import java.util.Properties;

import static org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent.Type.CHILD_UPDATED;

@SpringBootApplication
public class ZkConfigApplication implements ApplicationContextAware {


    private static ApplicationContext applicationContext;

    public static void main(String[] args) {

        SpringApplicationBuilder builder = new SpringApplicationBuilder(ZkConfigApplication.class);

        Map<String, Object> map = ZkUtils.initConfigIfEmpty();
        /**
         * 注册节点监听，对默认的命名空间监听，默认命名空间为application-config
         */
        NodeChangeListenerUtils.registerPathChildrenCacheListener("/", new TreeCacheListener() {
            @Override
            public void childEvent(CuratorFramework curatorFramework, TreeCacheEvent event) throws Exception {
                System.out.println("=====Config updated====" + event.getType());


                if (event.getType().equals(TreeCacheEvent.Type.NODE_UPDATED)) {
                    System.out.println("=====Config updated====");
                    DruidDataSource dataSource = applicationContext.getBean(DruidDataSource.class);

                    dataSource.restart();
                    dataSource.setUrl(ZkUtils.readConfigToProperties().getProperty("spring.datasource.url"));

                }
            }
        });

        builder.properties(map)
                .build().run(args);


    }


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }


}
